"""
依赖注入

提供FastAPI应用的依赖注入配置。
"""

from fastapi import FastAPI, Depends, HTTPException, Request
from typing import Optional, Dict, Any
import asyncio
from functools import lru_cache

from .config.settings import get_settings
from .agents.agent_registry import AgentRegistry
from .coordination.coordination_engine import CoordinationEngine
from .workflows.workflow_manager import WorkflowManager
from .data.data_manager import DataManager
from .data.data_quality import DataQualityChecker
from .data.data_cache import DataCache
from .coordination.task_analyzer import TaskAnalyzer
from .coordination.mode_selector import ModeSelector
from .coordination.conflict_resolver import ConflictResolver


@lru_cache()
def get_app_settings():
    """获取应用设置（缓存）"""
    return get_settings()


async def get_agent_registry(request: Request) -> AgentRegistry:
    """
    获取智能体注册器
    
    Args:
        request: HTTP请求对象
        
    Returns:
        智能体注册器实例
        
    Raises:
        HTTPException: 当智能体注册器不可用时
    """
    if not hasattr(request.app.state, 'agent_registry'):
        raise HTTPException(
            status_code=503,
            detail="智能体注册器不可用"
        )
    return request.app.state.agent_registry


async def get_coordination_engine(request: Request) -> CoordinationEngine:
    """
    获取协调引擎
    
    Args:
        request: HTTP请求对象
        
    Returns:
        协调引擎实例
        
    Raises:
        HTTPException: 当协调引擎不可用时
    """
    if not hasattr(request.app.state, 'coordination_engine'):
        raise HTTPException(
            status_code=503,
            detail="协调引擎不可用"
        )
    return request.app.state.coordination_engine


async def get_workflow_manager(request: Request) -> WorkflowManager:
    """
    获取工作流管理器
    
    Args:
        request: HTTP请求对象
        
    Returns:
        工作流管理器实例
        
    Raises:
        HTTPException: 当工作流管理器不可用时
    """
    if not hasattr(request.app.state, 'workflow_manager'):
        raise HTTPException(
            status_code=503,
            detail="工作流管理器不可用"
        )
    return request.app.state.workflow_manager


async def get_data_manager(request: Request) -> DataManager:
    """
    获取数据管理器
    
    Args:
        request: HTTP请求对象
        
    Returns:
        数据管理器实例
        
    Raises:
        HTTPException: 当数据管理器不可用时
    """
    if not hasattr(request.app.state, 'data_manager'):
        raise HTTPException(
            status_code=503,
            detail="数据管理器不可用"
        )
    return request.app.state.data_manager


async def get_data_quality_checker(request: Request) -> DataQualityChecker:
    """
    获取数据质量检查器
    
    Args:
        request: HTTP请求对象
        
    Returns:
        数据质量检查器实例
        
    Raises:
        HTTPException: 当数据质量检查器不可用时
    """
    if not hasattr(request.app.state, 'data_quality_checker'):
        raise HTTPException(
            status_code=503,
            detail="数据质量检查器不可用"
        )
    return request.app.state.data_quality_checker


async def get_data_cache(request: Request) -> DataCache:
    """
    获取数据缓存
    
    Args:
        request: HTTP请求对象
        
    Returns:
        数据缓存实例
        
    Raises:
        HTTPException: 当数据缓存不可用时
    """
    if not hasattr(request.app.state, 'data_cache'):
        raise HTTPException(
            status_code=503,
            detail="数据缓存不可用"
        )
    return request.app.state.data_cache


async def get_task_analyzer(request: Request) -> TaskAnalyzer:
    """
    获取任务分析器
    
    Args:
        request: HTTP请求对象
        
    Returns:
        任务分析器实例
        
    Raises:
        HTTPException: 当任务分析器不可用时
    """
    if not hasattr(request.app.state, 'task_analyzer'):
        raise HTTPException(
            status_code=503,
            detail="任务分析器不可用"
        )
    return request.app.state.task_analyzer


async def get_mode_selector(request: Request) -> ModeSelector:
    """
    获取模式选择器
    
    Args:
        request: HTTP请求对象
        
    Returns:
        模式选择器实例
        
    Raises:
        HTTPException: 当模式选择器不可用时
    """
    if not hasattr(request.app.state, 'mode_selector'):
        raise HTTPException(
            status_code=503,
            detail="模式选择器不可用"
        )
    return request.app.state.mode_selector


async def get_conflict_resolver(request: Request) -> ConflictResolver:
    """
    获取冲突解决器
    
    Args:
        request: HTTP请求对象
        
    Returns:
        冲突解决器实例
        
    Raises:
        HTTPException: 当冲突解决器不可用时
    """
    if not hasattr(request.app.state, 'conflict_resolver'):
        raise HTTPException(
            status_code=503,
            detail="冲突解决器不可用"
        )
    return request.app.state.conflict_resolver


async def get_current_user(request: Request) -> Optional[Dict[str, Any]]:
    """
    获取当前用户信息
    
    Args:
        request: HTTP请求对象
        
    Returns:
        用户信息字典或None
    """
    # 从会话中获取用户信息
    user_id = request.session.get("user_id")
    if not user_id:
        return None
    
    # 这里可以从数据库或缓存中获取完整的用户信息
    # 目前返回模拟数据
    return {
        "user_id": user_id,
        "username": f"user_{user_id}",
        "role": "analyst",
        "permissions": ["read", "write"]
    }


async def require_authentication(
    current_user: Optional[Dict[str, Any]] = Depends(get_current_user)
) -> Dict[str, Any]:
    """
    要求用户认证
    
    Args:
        current_user: 当前用户信息
        
    Returns:
        用户信息字典
        
    Raises:
        HTTPException: 当用户未认证时
    """
    if not current_user:
        raise HTTPException(
            status_code=401,
            detail="需要用户认证"
        )
    return current_user


async def require_permission(
    permission: str,
    current_user: Dict[str, Any] = Depends(require_authentication)
) -> Dict[str, Any]:
    """
    要求特定权限
    
    Args:
        permission: 所需权限
        current_user: 当前用户信息
        
    Returns:
        用户信息字典
        
    Raises:
        HTTPException: 当用户没有所需权限时
    """
    user_permissions = current_user.get("permissions", [])
    if permission not in user_permissions:
        raise HTTPException(
            status_code=403,
            detail=f"需要权限: {permission}"
        )
    return current_user


def require_admin_permission():
    """要求管理员权限的依赖"""
    async def _require_admin(
        current_user: Dict[str, Any] = Depends(require_authentication)
    ) -> Dict[str, Any]:
        if current_user.get("role") != "admin":
            raise HTTPException(
                status_code=403,
                detail="需要管理员权限"
            )
        return current_user
    
    return _require_admin


def require_analyst_permission():
    """要求分析师权限的依赖"""
    async def _require_analyst(
        current_user: Dict[str, Any] = Depends(require_authentication)
    ) -> Dict[str, Any]:
        allowed_roles = ["admin", "analyst", "trader"]
        if current_user.get("role") not in allowed_roles:
            raise HTTPException(
                status_code=403,
                detail="需要分析师或更高权限"
            )
        return current_user
    
    return _require_analyst


async def get_request_context(request: Request) -> Dict[str, Any]:
    """
    获取请求上下文
    
    Args:
        request: HTTP请求对象
        
    Returns:
        请求上下文字典
    """
    return {
        "request_id": getattr(request.state, 'request_id', None),
        "client_ip": request.client.host if request.client else None,
        "user_agent": request.headers.get("user-agent"),
        "method": request.method,
        "url": str(request.url),
        "headers": dict(request.headers)
    }


class ServiceHealthChecker:
    """服务健康检查器"""
    
    def __init__(self):
        self._health_cache = {}
        self._cache_ttl = 30  # 缓存30秒
    
    async def check_service_health(self, service_name: str, service_instance: Any) -> bool:
        """
        检查服务健康状态
        
        Args:
            service_name: 服务名称
            service_instance: 服务实例
            
        Returns:
            服务是否健康
        """
        import time
        current_time = time.time()
        
        # 检查缓存
        if service_name in self._health_cache:
            cached_time, cached_result = self._health_cache[service_name]
            if current_time - cached_time < self._cache_ttl:
                return cached_result
        
        # 执行健康检查
        try:
            if hasattr(service_instance, 'health_check'):
                is_healthy = await service_instance.health_check()
            else:
                # 默认认为服务健康
                is_healthy = True
            
            # 更新缓存
            self._health_cache[service_name] = (current_time, is_healthy)
            return is_healthy
            
        except Exception:
            # 健康检查失败
            self._health_cache[service_name] = (current_time, False)
            return False


# 全局健康检查器实例
health_checker = ServiceHealthChecker()


async def check_system_health(request: Request) -> Dict[str, Any]:
    """
    检查系统健康状态
    
    Args:
        request: HTTP请求对象
        
    Returns:
        系统健康状态字典
    """
    health_status = {
        "overall": "healthy",
        "services": {},
        "timestamp": "2024-01-01T00:00:00Z"
    }
    
    # 检查各个服务的健康状态
    services = [
        ("agent_registry", getattr(request.app.state, 'agent_registry', None)),
        ("coordination_engine", getattr(request.app.state, 'coordination_engine', None)),
        ("workflow_manager", getattr(request.app.state, 'workflow_manager', None)),
        ("data_manager", getattr(request.app.state, 'data_manager', None)),
        ("data_quality_checker", getattr(request.app.state, 'data_quality_checker', None)),
        ("data_cache", getattr(request.app.state, 'data_cache', None)),
        ("task_analyzer", getattr(request.app.state, 'task_analyzer', None)),
        ("mode_selector", getattr(request.app.state, 'mode_selector', None)),
        ("conflict_resolver", getattr(request.app.state, 'conflict_resolver', None))
    ]
    
    unhealthy_count = 0
    for service_name, service_instance in services:
        if service_instance is None:
            health_status["services"][service_name] = "unavailable"
            unhealthy_count += 1
        else:
            is_healthy = await health_checker.check_service_health(service_name, service_instance)
            health_status["services"][service_name] = "healthy" if is_healthy else "unhealthy"
            if not is_healthy:
                unhealthy_count += 1
    
    # 确定整体健康状态
    if unhealthy_count == 0:
        health_status["overall"] = "healthy"
    elif unhealthy_count < len(services):
        health_status["overall"] = "degraded"
    else:
        health_status["overall"] = "unhealthy"
    
    return health_status


def setup_dependencies(app: FastAPI) -> None:
    """
    设置应用依赖注入
    
    Args:
        app: FastAPI应用实例
    """
    # 这里可以添加全局依赖配置
    # 例如：app.dependency_overrides[get_settings] = lambda: custom_settings
    
    # 添加全局依赖（如果需要）
    # app.dependencies = [Depends(get_request_context)]
    
    import logging
    logger = logging.getLogger(__name__)
    logger.info("依赖注入配置完成")


# 常用依赖组合
CommonDependencies = {
    "agent_registry": Depends(get_agent_registry),
    "coordination_engine": Depends(get_coordination_engine),
    "workflow_manager": Depends(get_workflow_manager),
    "data_manager": Depends(get_data_manager),
    "data_quality_checker": Depends(get_data_quality_checker),
    "data_cache": Depends(get_data_cache),
    "task_analyzer": Depends(get_task_analyzer),
    "mode_selector": Depends(get_mode_selector),
    "conflict_resolver": Depends(get_conflict_resolver),
    "current_user": Depends(get_current_user),
    "request_context": Depends(get_request_context)
}

AuthenticatedDependencies = {
    **CommonDependencies,
    "current_user": Depends(require_authentication)
}

AdminDependencies = {
    **CommonDependencies,
    "current_user": Depends(require_admin_permission())
}

AnalystDependencies = {
    **CommonDependencies,
    "current_user": Depends(require_analyst_permission())
}